<template>
  <div :id="id" :style="{width: width, height: height}"></div>
</template>
<script>
import { ref, defineComponent } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'echarts',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    id: String,
    option: Object
  },
  data () {
    return {
      chart: null
    }
  },
  mounted () {
    this.initChart();
    const self = this;
    window.addEventListener('resize', function () {
      self.resize();
    });
  },
  methods: {
    initChart () {
      this.chart = echarts.init(document.getElementById(this.id), 'light');
    },
    resize () {
      this.chart && this.chart.resize();
    }
  },
  watch: {
    option: {
      handler (val) {
        if (!this.chart) {
          this.initChart();
        }

        if (val && Object.keys(val).length > 0) {
          this.chart.setOption(val);
        }
      },
      deep: true
    }
  }
})
</script>
